package github.sf.fw.tools.var;

import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 变量池
 */
public class VariablePool {
    private final ConcurrentHashMap<String, Variable> globalVariablePool = new ConcurrentHashMap<>();

    public VariablePool() {
    }

    public VariablePool(Collection<Variable> variables) {
        for (Variable variable : variables) {
            Objects.requireNonNull(variable);
            globalVariablePool.put(getVariableName(variable), variable);
        }
    }

    public Variable getVariable(String variableName) {
        if (VarUtil.checkVarName(variableName, false)) {
            variableName = VarUtil.unwrap(variableName);
        }
        return globalVariablePool.get(variableName);
    }

    public void addVariableToPool(Variable variable) {
        Objects.requireNonNull(variable);
        globalVariablePool.put(getVariableName(variable), variable);
    }

    private String getVariableName(Variable variable) {
        String variableName = variable.getVariableName();
        if (VarUtil.checkVarName(variableName, false)) {
            variableName = VarUtil.unwrap(variableName);
        }
        return variableName;
    }
}
